using System.Buffers;
using SuperSocket.ProtoBase;

namespace Core;

public sealed class PlayPacketEncode : IPackageEncoder<PlayPacket>
{
    private static readonly Dictionary<Type, CommandKey> Packets = new();
    private const int HeaderSize = sizeof(short);
    private const byte CmdSize = sizeof(byte);

    static PlayPacketEncode()
    {
        var commands = PlayPacket.CommandTypes.ToDictionary(keySelector => keySelector.Value, elementSelector => elementSelector.Key);

        foreach (var command in commands)
            Packets.Add(command.Key, command.Value);
    }

    public int Encode(IBufferWriter<byte> writer, PlayPacket pack)
    {
        var cmd = Packets[pack.GetType()];
        var body = pack.EncodeBody();
        var bodyLength = body.Length + CmdSize;

        writer.WriteInt16LittleEndian((short)bodyLength); // body 的长度
        writer.WriteByteBigEndian((byte)cmd); //命令 
        writer.Write(body); // 内容

        return HeaderSize + bodyLength;
    }
}